package org.dromara.exam.consumer;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.redis.utils.QueueUtils;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.sse.dto.SseMessageDto;
import org.dromara.common.sse.utils.SseMessageUtils;
import org.dromara.exam.domain.dto.Task;
import org.dromara.exam.domain.vo.ExamTemplateVo;
import org.dromara.exam.service.IExamTemplateService;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @author xiyin321
 * @since 2025/2/16
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class QuestionGenConsumer {

    private final IExamTemplateService examQuestionService;
    private final Executor asyncExecutor = Executors.newFixedThreadPool(8);

    @PostConstruct
    public void init() {
        QueueUtils.subscribeBlockingQueue("exam:gen:queue", this::processTask, false);
        log.info("增加题目生成队列消费者");
    }

    private CompletionStage<Void> processTask(Task task) {
        CompletableFuture.runAsync(() -> {
            try {
                List<ExamTemplateVo> result = examQuestionService.generateQuestionList(task.getBo());
                RedisUtils.setCacheObject(
                    "exam:gen:status:" + task.getTaskId(),
                    result,
                    Duration.ofSeconds(600)
                );
                // 推送成功消息
                SseMessageUtils.sendMessage(task.getUserId(),"题目生成结束");
            } catch (Exception e) {
                SseMessageUtils.sendMessage(task.getUserId(),"题目生成错误");
            }
            // 使用独立线程池执行
        }, asyncExecutor);
        return CompletableFuture.completedFuture(null);
    }
}
